from flask import Flask, render_template, request,send_file
from pytube import YouTube
import json
import re

app = Flask(__name__)

yt = None

@app.route('/', methods=['GET', 'POST'])
def index():

    return render_template('index.html')


@app.route('/getVideoMsg', methods=['POST'])
def getVideoMsg():
    if request.method == 'POST':
        # 获取前端的数据video_input
        url = request.form.get('video_input')
        print(url)
        
        if not url :
            return render_template('index.html',status=False)
        data = get_msg_by_url(url)
        if not data:
            return render_template('index.html',status=False)

        backend_data =  simulate_backend_processing(data)
        return render_template('index.html',status=True,options=backend_data)

# 根据itag 下载视频资源
@app.route('/getVideo', methods=['POST'])
def getVideo():
    itag = request.form.get('videoForm')
    print(itag)
    if not itag or not str(itag).isdigit():
        return render_template('index.html',status=False)
    print('downloading video starting...')
    stream = yt.streams.get_by_itag(int(itag))
    video_path = stream.download()

    # 将下载的视频文件发送给用户
    return send_file(video_path, as_attachment=True)

# 解包视频信息
def simulate_backend_processing(data):
    backend_data = []
    for d in data:
        backend_data.append([d.itag,d.mime_type,d.resolution])
    return backend_data

# 使用re校验判断url是否合法
def isValidURL(url):
    # 正则表达式模式，匹配常见的URL格式
    url_pattern = r'^(https?|ftp)://[^\s/$.?#].[^\s]*$'
    
    # 使用re.match()检查URL是否匹配模式
    if re.match(url_pattern, url):
        return True
    else:
        return False

# 根据url 获取 YouTube视频信息
def get_msg_by_url(url):
    global yt
    if not isValidURL(url):
        return False
    yt = YouTube(url=url)
    streamlist = yt.streams.filter(file_extension='mp4',progressive=True)
    return streamlist

if __name__ == '__main__':
    app.run(debug=False)
